package com.sikadwafastdaisfondturbo.pretloan.ui.user.page

import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaOnItemChildClickListener
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.ProcessAccountAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageAccountFrenchBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BindCardAddDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BindCardDeleteDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BindCardOtherDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.LinearDecoration
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/24 20:03
 * @Annotation：我的账户 - 法语
 */
class AccountFrenchPage: ProFragment() {
    private var _binding: PageAccountFrenchBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    //绑卡列表
    private var mAccountAdapter: ProcessAccountAdapter? = null

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageAccountFrenchBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        initRefreshLayout()
        initRecyclerView()
    }

    override fun initListener() {
        //新增
        _binding?.addLayout?.setOnClickListener {
            showBindCardDialog()
        }
    }

    override fun initData() {
        showLoading()
        loadAccountListAction()
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            loadAccountListAction()
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化绑卡列表
     */
    private fun initRecyclerView() {
//        _binding?.recyclerView?.setHasFixedSize(true)
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        _binding?.recyclerView?.layoutManager = LinearLayoutManager(context)
        mAccountAdapter = ProcessAccountAdapter(_binding?.recyclerView)
        val topDecoration = DensityUtils.dp2px(14f)
        _binding?.recyclerView?.addItemDecoration(LinearDecoration(0,0,topDecoration,topDecoration))
        _binding?.recyclerView?.adapter = mAccountAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        mAccountAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { parent, childView, position ->
            when(childView.id){
                R.id.editLayout -> {//编辑
                    showBindCardDialog()
                }
                R.id.bindedLayout -> {//查看已绑卡
//                    showToast("查看")
                }
                R.id.deleteLayout -> {//删除
                    showDeleteDialog(position)
                }
            }
        })
    }

    /**
     * 添加绑卡dialog
     */
    private fun showBindCardDialog(){
        addEvent(EventType.CLICK.CLICK_USER_ACCOUNT_ADD,"UserAccount Page")
        val bindCardDialog = BindCardAddDialog(context,"UserAccount Page",object : BindCardAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                submitBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.show()
    }

    /**
     * 设置已绑定的账号列表
     */
    fun setBindAccountList(accountList: ArrayList<JSONObject>) {
        accountList.forEach {
            it.put("isShowDelete",true)
        }
        mAccountAdapter?.data = accountList
    }

    /**
     * 提示绑定另一个渠道账户
     */
    fun showBingAccountOtherDialog(otherInfo: JSONObject?) {
        otherInfo?.let {
            val replaceDialog = BindCardOtherDialog(context,"UserAccount Page",object : BindCardOtherDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnConfirm){//添加
                        submitBindAccountAction(it.optString("walletMobile"),it.optString("value"), "YES")
                    }
                }
            })
            replaceDialog.show()
            replaceDialog.setBindAccountInfo(it)
        }
    }

    /**
     * 删除提示
     */
    private fun showDeleteDialog(position: Int){
        mAccountAdapter?.let {
            val item = it.getItem(position)
            addEvent(EventType.CLICK.CLICK_USER_ACCOUNT_DELETE,item.optString("id"))
            val deleteDialog = BindCardDeleteDialog(context,"UserAccount Page",object : BindCardDeleteDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnSubmit){
                        deleteAccountAction(item)
                    }
                }
            })
            deleteDialog.show()
            deleteDialog.setBindAccountInfo(item)
        }
    }

    /**
     * 获取账户列表
     */
    private fun loadAccountListAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.ACCOUNT_LIST_FRENCH)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val accountList = arrayListOf<JSONObject>()
                val array = data.optJSONArray("obj")

                if (array != null && array.length() > 0) {
                    for (i in 0..<array.length()) {
                        val item = array.optJSONObject(i)
                        item.put("isEdit", false)
                        accountList.add(item)
                    }
                }

                if (accountList.size < 2) {
                    for (i in 0..<2 - accountList.size) {
                        val item = JSONObject()
                        item.put("isEdit", true)
                        accountList.add(item)
                    }
                }
                setBindAccountList(accountList)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                _binding?.refreshLayout?.finishRefresh()
            }
        })
    }

    /**
     * 添加绑卡
     */
    fun submitBindAccountAction(mobile: String, walletChannel: String, bindFlag:String = "NO") {
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.ACCOUNT_ADD)
            put("walletMobile", mobile)
            put("walletMobileConfirm", mobile)
            put("walletChannel", walletChannel)
            put("addBindFlag", bindFlag)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadAccountListAction()

                val obj = data.optJSONObject("obj") ?: JSONObject()

                // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                val addBindFlag = obj.optString("addBindFlag")
                if (addBindFlag == "YES") {
                    //需要提示绑定另一个渠道账户
                    var otherAccountInfo: JSONObject? = null

                    //用于从APP配置中获取（walletChannels）对应的信息
                    val channel = obj.optString("channel")
                    if (channel.isNotBlank()) {
                        val spData = Configs.getSPString(Configs.SPKEY.SIKADWA_COMMON)
                        val commonData = JSONObject(spData)
                        val customize = commonData.optJSONObject("customize")
                        if (customize != null) {
                            val walletChannels = customize.optJSONArray("walletChannels")
                            if (walletChannels != null && walletChannels.length() > 0) {
                                for (i in 0..<walletChannels.length()) {
                                    val item = walletChannels.optJSONObject(i)
                                    if (channel == item.optString("value")) {
                                        otherAccountInfo = item
                                        break
                                    }
                                }
                            }

                            // 只有非空的情况下才处理
                            if (otherAccountInfo != null) {
                                otherAccountInfo.put("walletMobile", mobile)
                                //提示绑定另一个渠道账户
                                showBingAccountOtherDialog(otherAccountInfo)
                                return
                            }
                        }
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 删除账户
     */
    fun deleteAccountAction(data: JSONObject) {
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.ACCOUNT_DELETE)
            put("ids", data.optString("id"))
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                showToast(data.optString("msg"))
                //刷新列表
                loadAccountListAction()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }
}